package notes.java.java8.demo.streams;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/** 去重*/
public class S4_Distinct {

	public static void main(String[] args) {
		// 测试数据
		List<String> datas = new ArrayList<>(Arrays.asList("AA", "BB", "AA", "CC", "BB"));
		
		// 去重
		List<String> list = datas.stream().distinct().collect(Collectors.toList());
		
		// 输出
		list.forEach(System.out::println);
		
		// 测试数据
		List<Book> books = new ArrayList<>();
		Book java = new Book("java", 58.66);
		books.add(java);
		
		Book javax = new Book("java", 58.66);
		books.add(javax);
		
		Book c = new Book("c++", 55.02);
		books.add(c);
		
		// 去重(根据书名)
		List<Book> bks = books.stream().filter(distinctByKey(Book::getName)).collect(Collectors.toList());
		
		// 输出
		bks.forEach(b->{
			System.out.println(b.getName() + "\t" + b.getPrice());
		});
		
	}
	
	/** 根据key去重 */
	private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Map<Object,Boolean> seen = new ConcurrentHashMap<>();
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }
}

class Book {
	
	private String name;
	private double price;
	
	public Book(String name, double price) {
		super();
		this.name = name;
		this.price = price;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	
}
